package com.googlecode.garbagecan.jsonstudy.gson;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.googlecode.garbagecan.jsonstudy.User;

import java.lang.reflect.Type;
import java.util.*;

public class GsonTest {
	public static void main(String[] args) {
		testBean();
		testList();
		testMap();
	}

	private static void testBean() {
		System.out.println("test bean ...");
		Gson gson = new Gson();
		User user = new User();
		user.setUsername("Mandy");
		user.setPassword("Mandy");
		user.setBirthday(Calendar.getInstance().getTime());

		String json = gson.toJson(user);
		System.out.println(json);
		System.out.println(gson.fromJson(json, User.class));
	}

	private static void testList() {
		System.out.println("test list ...");
		List<User> users = new ArrayList<User>();
		for (int i = 0; i < 5; i++) {
			User user = new User();
			user.setUsername("user_" + i);
			user.setPassword("password_" + i);
			user.setBirthday(Calendar.getInstance().getTime());
			users.add(user);
		}
		Type listType = new TypeToken<List<User>>() {}.getType();

		Gson gson = new Gson();
		String json = gson.toJson(users, listType);
		System.out.println(json);
		users = gson.fromJson(json, listType);
		System.out.println(users);
	}

	private static void testMap() {
		System.out.println("test map ...");
		Map<String, User> users = new LinkedHashMap<String, User>();
		for (int i = 0; i < 5; i++) {
			User user = new User();
			user.setUsername("user_" + i);
			user.setPassword("password_" + i);
			user.setBirthday(Calendar.getInstance().getTime());
			users.put(user.getUsername(), user);
		}
		Type mapType = new TypeToken<Map<String, User>>() {}.getType();

		Gson gson = new Gson();
		String json = gson.toJson(users, mapType);
		System.out.println(json);
		users = gson.fromJson(json, mapType);
		System.out.println(users);
	}
}
